import Watcher from "../Framework/scripts/Watcher";
const { ccclass, property } = cc._decorator;

@ccclass
export default class GameAssetMgr extends cc.Component {

    public static instance: GameAssetMgr = null;
    public static readonly SpriteLoadedEvent = "SpriteLoaded";


    onLoad() {
        GameAssetMgr.instance = this;
        this.loadSprites();
    }
    private async loadSprites() {

        const spriteCache = this.spriteCache;
        const context = this;
        const urls = [
            "item",
            "fonts/combo"
        ];
        let sum = urls.length;
        let i = 0;
        for (let url of urls) {
            cc.loader.loadResDir(url, cc.SpriteFrame, function (error: Error, resource: any[], urls: string[]) {
                if (!error) {
                    for (let sf of resource) {
                        //let name = sf._texture.url;
                        let name = sf.name;
                        spriteCache[name] = sf;
                    }
                    if (++i == sum) {
                        context.resloadComplete();
                    }
                }
            });
        }
    }

    private _spriteLoaded = false;
    public get spriteLoaded(){
        return this._spriteLoaded;
    }
    private resloadComplete() {
        console.log(">>>>纹理加载完成");
        this._spriteLoaded = true;
        Watcher.dispatch(GameAssetMgr.SpriteLoadedEvent);
    }
    private spriteCache: { [gid: number]: cc.SpriteFrame } = {};
    public getSpriteByID(id): cc.SpriteFrame | undefined {
        return this.spriteCache[id];
    }
}
